#coding=utf-8
import re,logging,os,urllib,time,random
from google.appengine.api import mail
from google.appengine.ext import db,webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.api.labs import taskqueue

from ad import get_latest_ad, send_ad
from name import SENDERS
from qq import QQ

APPLICATION = os.environ['APPLICATION_ID']
SERVER = '%s.appspotmail.com'%APPLICATION
EMAIL_PORTAL_URL = 'http://email-portal.appspot.com/get'
RE_EMAIL = re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",re.IGNORECASE)

class RejectedEmail(db.Model):
  addr = db.StringProperty(required=True)
  flag = db.BooleanProperty(default=False)   
  
def get_sender():
  sender = random.choice(SENDERS)
  return '%s@%s'%(sender, SERVER)

class MailSender(webapp.RequestHandler):
  def get(self):
    addr = self.request.get('email')
    
    ad = get_latest_ad()
    send_ad(ad, sender=get_sender(), receiver=addr)
    logging.debug( '%s Sended'%addr )
    self.response.out.write(addr)

class MailSender2(webapp.RequestHandler):
  def get(self):
    if QQ.all().filter('flag =', False).count() == 0:
      return
    q = QQ.all().filter('flag =', False).fetch(1)[0]
    email = '%s@qq.com'%q.code    
    
    ad = get_latest_ad()
    send_ad(ad, sender=get_sender(), receiver=email)
    
    q.flag = True
    q.save()
    
    self.response.out.write(email)

class MailSender3(webapp.RequestHandler):
  def get(self):
    addr = self.request.get('email')
    mail.send_mail(sender=get_sender(),
      to=addr,
      subject='hello',
      body='hello', 
      html='hello')
    self.response.out.write(addr)

class MailHandler(InboundMailHandler):
  def receive(self, message):
    _subject = message.subject
    _sender = message.sender
    bodies = message.bodies(content_type='text/plain')
    allBodies = "";
    for body in bodies:
        allBodies = allBodies + "\n---------------------------\n" + body[1].decode()  
    
    if allBodies.find('answer=69585') != -1:
      change_sender()
      logging.critical('Sender Changed!')      
      
    info = '发送者:%s\n标题:%s\n正文:%s\n'%(_sender, _subject, allBodies)
    logging.info(info)
        
    addrs = []
    emails = RE_EMAIL.findall(allBodies)
    #logging.info('*'.join(emails))
    for e in emails:
      if not e:continue
      e2 = e.strip()
      if e2.split('@')[-1] in [SERVER, 'google.com']:
          continue
      addrs.append(e2)
    addrs = list(set(addrs))
    #logging.info('~'.join(addrs))
    for addr in addrs:
      RejectedEmail(addr=addr).put()

def post_rejected(email, subject='s', content='c'):
  import urllib
  import urllib2

  url = 'http://remail.cndjango.com/reject'
  values = {'email': email,
            'sub': subject,
            'content': content
            }
  
  data = urllib.urlencode(values)
  req = urllib2.Request(url, data)
  response = urllib2.urlopen(req)
  the_page = response.read()
  return the_page

class PostRejected(webapp.RequestHandler):
  def get(self):
    n = RejectedEmail.all().count()
    if n == 0:return
    
    r = RejectedEmail.all().fetch(1)[0]
    post_rejected(r.addr)
    r.delete()
    self.response.out.write(r.addr)
    
      
      
